import subprocess, sys
import time
from data.globalData import GDat, GObject, GObj
from debug.debugOut import log


# 连接热点
def connect_to_hotspot(ssid: str, password: str):
    try:
        if not GObj.wifi.is_wifi_enabled():  # 判断是否已开启wifi
            GObj.wifi.open_wifi()  # 打开WiFi
            # 等待WiFi启用完成
            for i in range(10):  # 最多等待10秒
                if GObj.wifi.is_wifi_enabled():
                    log.debug("WiFi已启用")
                    break
                time.sleep(1)
            else:
                log.error("WiFi启用超时")
                return False

        # 尝试连接到热点
        result = GObj.wifi.connect_to_hotspot(ssid, password)
        if result:
            log.info(f"成功连接到热点 {ssid}")
        else:
            log.error(f"连接到热点 {ssid} 失败")
        return result
    except Exception as e:
        log.error(f"连接到热点 {ssid} 失败: {e}")
        return False


# 读取 shell 环境变量
def read_shell_env():
    try:
        pid = subprocess.check_output(["pgrep","-n","gnome-shell"]).decode().strip()
    except subprocess.CalledProcessError:
        print("未找到 gnome-shell 进程；请先登录图形桌面。", file=sys.stderr)
        sys.exit(3)
    env = {}
    with open(f"/proc/{pid}/environ","rb") as f:
        for kv in f.read().split(b"\x00"):
            if b"=" in kv:
                k,v = kv.split(b"=",1)
                env[k.decode()] = v.decode()
    return {k: env.get(k,"") for k in GDat.NEEDED}

# 启动浏览器
def start_browser():
    shell_env = read_shell_env()

    # 构造 systemd-run 命令（显式传入桌面会话环境）
    cmd = [
        "systemd-run","--user","--collect","--quiet",
        *(f"--setenv={k}={v}" for k,v in shell_env.items() if v),
        "/usr/bin/firefox","--kiosk", GDat.HomeAssistant_URL  # 全屏
        # "/usr/bin/firefox", URL   # 普通模式
    ]


    rc = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode
    if rc != 0:
        print("没能在用户会话中启动浏览器。", file=sys.stderr)
        sys.exit(2)